import {defer, reactive, useRefs} from "plain-design-composition";
import {PlForm, PlFormItem, PlInput, useDialog} from "plain-design";
import React from "react";

export function useGetRouteParams() {
    const $dialog = useDialog()
    const {refs, onRef} = useRefs({form: PlForm})

    async function getIdAndCode() {
        const dfd = defer<{ id: string, code: string }>()
        const state = reactive({
            formData: {id: '', code: ''}
        })
        const opt = $dialog({
            title: '路由参数',
            confirmButton: true,
            cancelButton: true,
            dialogProps: {
                width: null as any,
                closeOnConfirm: false,
            },
            render: () => <>
                <PlForm modelValue={state.formData} ref={onRef.form}>
                    <PlFormItem label="动态路由参数id" field="id" required>
                        <PlInput v-model={state.formData.id}/>
                    </PlFormItem>
                    <PlFormItem label="动态路由参数code" field="code" required>
                        <PlInput v-model={state.formData.code}/>
                    </PlFormItem>
                </PlForm>
            </>,
            onConfirm: async () => {
                await refs.form?.validate()
                dfd.resolve(state.formData)
                opt.close()
            },
            onCancel: dfd.reject,
        })
        return dfd.promise
    }

    return {getIdAndCode}
}